package top.frsf.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import top.frsf.reggie.common.BaseContext;
import top.frsf.reggie.dto.OrdersDto;
import top.frsf.reggie.entity.*;
import top.frsf.reggie.excpetion.BusinessException;
import top.frsf.reggie.mapper.OrdersMapper;
import top.frsf.reggie.service.*;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 订单表(Orders)表服务实现类
 *
 * @author makejava
 * @since 2023-01-29 19:53:50
 */
@Service("ordersService")
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * @Author: FRSF
     * @Date: 2023/1/29 23:40
     * @Description 用户下单
     * @param orders:
     * @return: void
     */
    @Override
    public void submit(Orders orders) {
        // 1.获取当前用户ID
        Long userId = BaseContext.getCurrentId();

        // 2.查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);
        if (shoppingCarts.isEmpty()) {
            throw new BusinessException("购物车为空，不能下单");
        }
        // 订单号
        long orderId = IdWorker.getId();
        // 计算金额，返回订单明细
        // 原子操作
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        // 3.orders插入数据(1条)
        // 用户数据查询
        User user = userService.getById(userId);
        // 地址数据
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        // 计算金额
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        this.save(orders);

        // 4.orders_detail插入数据(多条)
        orderDetailService.saveBatch(orderDetails);

        // 5.下单完成，清空购物车
        shoppingCartService.remove(wrapper);
    }


    /**
     * @Author: FRSF
     * @Date: 2023/2/12 21:01
     * @Description 订单分页查询，将已经查询完成的ordersPage，转换为ordersDtoPage
     * @param ordersPage:
     * @param ordersDtoPage:
     * @return: void
     */
    @Override
    public void pageByDto(Page<Orders> ordersPage, Page<OrdersDto> ordersDtoPage) {
        // page对象拷贝
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        // dto 订单detail集合
        List<OrdersDto> records = new ArrayList<>();
        ordersDtoPage.setRecords(records);

        for (Orders record : ordersPage.getRecords()) {
            // 查询当前订单ID下的orderDetail
            LambdaQueryWrapper<OrderDetail> detailWrapper = new LambdaQueryWrapper<>();
            detailWrapper.eq(OrderDetail::getOrderId, record.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(detailWrapper);

            // 构造orderDto，设置已查询的orderDetail
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(record, ordersDto);
            // 设置 用户名、电话、地址、签收人
            User byId = userService.getById(record.getUserId());
            ordersDto.setUserName(record.getUserName());
            ordersDto.setPhone(record.getPhone());
            ordersDto.setAddress(record.getAddress());
            ordersDto.setConsignee(record.getConsignee());
            ordersDto.setOrderDetails(orderDetails);

            // 存入dto Records内
            records.add(ordersDto);
        }

    }

}

